package com.jdew.thkj.activity;

import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.view.ViewPager;
import android.util.DisplayMetrics;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.jdew.thkj.R;
import com.jdew.thkj.adapter.MyViewpagerAdapter;
import com.jdew.thkj.adapter.MyVpAdater;
import com.jdew.thkj.base.BaseActivity;
import com.jdew.thkj.bean.NewCodeBean;
import com.jdew.thkj.bean.ShareCodeBean;
import com.jdew.thkj.manager.ActivityManagerUtils;
import com.jdew.thkj.manager.AppConfig;
import com.jdew.thkj.manager.MyGallyPageTransformer;
import com.jdew.thkj.manager.ShareManager;
import com.jdew.thkj.network.RetrofitManager;
import com.jdew.thkj.network.api.RequestApi;
import com.jdew.thkj.utils.MD5Utils;
import com.jdew.thkj.utils.RegexValidateUtils;
import com.jdew.thkj.wxapi.WechatShareManeger;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * Created by yangzai on 2018/4/18 0018.
 */

public class MineErCodeActivity extends BaseActivity implements View.OnClickListener {
    @Bind(R.id.vp)
    ViewPager vp;
    @Bind(R.id.back)
    ImageView back;
    @Bind(R.id.title)
    TextView title;
    @Bind(R.id.wx)
    TextView wx;
    @Bind(R.id.friend_cricle)
    TextView friendCricle;
    @Bind(R.id.save)
    TextView save;
    @Bind(R.id.tv_cancel)
    TextView tvCancel;
    @Bind(R.id.shareView)
    LinearLayout shareView;
    private WechatShareManeger mShareManager;
    private SharedPreferences sp;
    private String userCode = "CP97DWN8";
    private List<String> images = new ArrayList<>();
    private ShareManager shareManager;
    private List<String> shareList = new ArrayList<>();
    private int position;
    private Bitmap shareBitmap;
    private String shareurl;
    private int width, height;
    private MyVpAdater adater;

    @Override
    public int bindLayout() {
        return R.layout.activity_ercode;
    }

    @Override
    public void initView(View view) {
        title.setText("分享海报");
        back.setVisibility(View.VISIBLE);
        mShareManager = WechatShareManeger.getInstance(this);
        back.setOnClickListener(this);
        wx.setOnClickListener(this);
        friendCricle.setOnClickListener(this);
        save.setOnClickListener(this);
        save.setText("保存图片");
        sp = getSharedPreferences("user", MODE_PRIVATE);
        mShareManager = WechatShareManeger.getInstance(this);
        tvCancel.setVisibility(View.GONE);
        DisplayMetrics dm = getResources().getDisplayMetrics();
        height = dm.heightPixels;
        width = dm.widthPixels;
        LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) vp.getLayoutParams();
        params.width = width;//设置当前控件布局的宽度
        params.height = height - 100;
        vp.setLayoutParams(params);
        changeStatusBarTextColor();
        OutUserCode();
    }

    public void GetPosterInfo() {
        String timesamp = RegexValidateUtils.getTime13();
        String numsamp = RegexValidateUtils.getRandom10();
        String logourl = sp.getString("UserImgUrl", "").equals("") ? "https://tlhadmin.oss-cn-hangzhou.aliyuncs.com/Image/63679199182205.jpg" : sp.getString("UserImgUrl", "");
        RetrofitManager.getInstance(AppConfig.BASE_URL)
                .createReq(RequestApi.class).GetPosterInfo(userCode, logourl, RegexValidateUtils.getUniquePsuedoID(), timesamp, numsamp, MD5Utils.getMD5(RegexValidateUtils.ASCIISort(timesamp + numsamp + RegexValidateUtils.getUniquePsuedoID() + sp.getString("SignToken", "") + "code" + userCode + "logoUrl" + logourl)).toUpperCase()).observeOn(AndroidSchedulers.mainThread()).subscribeOn(Schedulers.io()).subscribe(new Subscriber<ShareCodeBean>() {
            @Override
            public void onCompleted() {
            }

            @Override
            public void onError(Throwable e) {
            }

            @Override
            public void onNext(ShareCodeBean bean) {
                if (bean.getCode().equals("0")) {
                    if (null != shareList && shareList.size() != 0) {
                        shareList.clear();
                    }
                    shareList.addAll(bean.getData());
                    vp.setOffscreenPageLimit(shareList.size());
                    int pagerWidth = (int) (getResources().getDisplayMetrics().widthPixels * 3.0f / 4.0f);
                    ViewGroup.LayoutParams lp = vp.getLayoutParams();
                    if (lp == null) {
                        lp = new ViewGroup.LayoutParams(pagerWidth, ViewGroup.LayoutParams.MATCH_PARENT);
                    } else {
                        lp.width = pagerWidth;
                    }
                    vp.setLayoutParams(lp);
                    vp.setPageMargin(getResources().getDimensionPixelSize(R.dimen.activity_horizontal_margin));
                    vp.setPageTransformer(true, new MyGallyPageTransformer());
                    adater = new MyVpAdater(MineErCodeActivity.this, shareList);
                    vp.setAdapter(adater);
                    vp.setPageMargin(40);
                    vp.setOffscreenPageLimit(shareList.size());
                    shareView.setVisibility(View.VISIBLE);
                }
            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.back: {
                finish();
            }
            break;
            case R.id.wx: {
                position = vp.getCurrentItem();
                share(0, "", "wx");
            }
            break;
            case R.id.friend_cricle: {
                position = vp.getCurrentItem();
                shareurl = shareList.get(position);
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        if (!shareurl.equals("") && null != shareurl) {
                            shareBitmap = RegexValidateUtils.returnBitmap(shareurl);
                            mShareManager.sharePicture(1, shareBitmap);
                        }
                    }
                }).start();
            }
            break;
            case R.id.save: {
                position = vp.getCurrentItem();
                images.add(shareList.get(position));
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        final String url = shareList.get(position);
                        new Thread(new Runnable() {
                            @Override
                            public void run() {
                                if (!url.equals("") && null != url) {
                                    if (null != shareBitmap) {
                                        shareBitmap.recycle();
                                    }
                                    shareBitmap = RegexValidateUtils.returnBitmap(url);
                                    RegexValidateUtils.saveBmp2Gallery(MineErCodeActivity.this, shareBitmap);
                                }
                            }
                        }).start();
                    }
                }, 100);
                Toast.makeText(this, "图片保存成功，请进入相册查看", Toast.LENGTH_SHORT).show();
            }
            break;
            default:
                break;
        }
    }


    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        ActivityManagerUtils.popActivity(this);
    }

    private void changeStatusBarTextColor() {
        if (Build.VERSION.SDK_INT >= 21) {
            Window window = this.getWindow();
            window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            getWindow().setStatusBarColor(getResources().getColor(R.color.color_ffffff));
            window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);//设置状态栏黑色字体
        }
    }

    public void OutUserCode() {
        String timesamp = RegexValidateUtils.getTime13();
        String numsamp = RegexValidateUtils.getRandom10();
        HashMap<String, Object> map = new HashMap();
        map.put("Id", sp.getString("userId", ""));
        RetrofitManager.getInstance(AppConfig.BASE_URL).createReq(RequestApi.class).OutUserCode(map, RegexValidateUtils.getUniquePsuedoID(), timesamp, numsamp, MD5Utils.getMD5(RegexValidateUtils.ASCIISort(timesamp + numsamp + RegexValidateUtils.getUniquePsuedoID() + sp.getString("SignToken", "") + "Id" + sp.getString("userId", ""))).toUpperCase()).observeOn(AndroidSchedulers.mainThread()).subscribeOn(Schedulers.io()).subscribe(new Subscriber<NewCodeBean>() {
            @Override
            public void onCompleted() {
            }

            @Override
            public void onError(Throwable e) {
//                GetPosterInfo();
            }

            @Override
            public void onNext(NewCodeBean bean) {
                if (bean.getCode().equals("0")) {
                    userCode = bean.getData().getUserCode();
                    GetPosterInfo();
                }
            }
        });
    }

    public static Bitmap netUrlPicToBmp(String src) {
        try {

            URL url = new URL(src);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setDoInput(true);
            connection.connect();
            InputStream input = connection.getInputStream();
            Bitmap myBitmap = BitmapFactory.decodeStream(input);

            //设置固定大小
            //需要的大小
            float newWidth = 200f;
            float newHeigth = 200f;

            //图片大小
            int width = myBitmap.getWidth();
            int height = myBitmap.getHeight();

            //缩放比例
            float scaleWidth = newWidth / width;
            float scaleHeigth = newHeigth / height;
            Matrix matrix = new Matrix();
            matrix.postScale(scaleWidth, scaleHeigth);

            Bitmap bitmap = Bitmap.createBitmap(myBitmap, 0, 0, width, height, matrix, true);
            return bitmap;
        } catch (IOException e) {
            // Log exception
            return null;
        }
    }

    private void share(int i, String s, String mType) {
        if (null != images && images.size() > 0) {
            images.clear();
        }
        images.add(shareList.get(position));
        shareManager = new ShareManager(this);
        shareManager.setShareImage(i, images, s, mType);
    }

}
